const router = require("koa-router")();
const userList = [
  {
    tel: "13111111111",
    username: "admin",
    password: "admin",
    avator: "https://robohash.org/1231231",
    nickname: "苦快乐的管理员",
  },
  {
    tel: "13222222222",
    username: "test",
    password: "test",
    avator: "https://robohash.org/555",
    nickname: "德国温泉我",
  },
  {
    tel: "13333333333",
    username: "user",
    password: "user",
    avator: "https://robohash.org/567654",
    nickname: "反驳为你佛我去二",
  },
];
let _code = null;
router.post("/login", function (ctx) {
  const { username, password } = ctx.request.body;

  const item = userList.find(
    (v) => v.username === username && v.password === password
  );

  if (item) {
    // 存在
    ctx.body = {
      code: 200,
      data: {
        userInfo: item,
      },
      message: "登陆成功",
    };
  } else {
    // 不存在
    ctx.body = {
      code: 401,
      data: null,
      message: "账号密码错误， 请重新登录",
    };
  }
});

router.get("/login/getCode", (ctx) => {
  const { tel } = ctx.request.query;
  const item = userList.find((v) => v.tel === tel);
  if (item) {
    //存在  返回验证码
    _code = Math.random().toString(36).slice(2, 6);
    ctx.body = {
      code: 200,
      data: _code,
      message: "获取验证码成功",
    };
  } else {
    // 不存在  自动注册用户  返回验证码
    userList.push({
      tel: tel,
      nickname: "随便默认用户",
      avator:
        "https://www.gexingzu.com/d/file/p/20230401/16819490259271574.jpg",
    });
    _code = Math.random().toString(36).slice(2, 6);
    ctx.body = {
      code: 200,
      data: _code,
      message: "登陆成功",
    };
  }
});

router.post("/login/tel", (ctx) => {
  const { tel, code } = ctx.request.body;
  const item = userList.find((v) => v.tel === tel);
  if (item) {
    if (code === _code) {
      ctx.body = {
        code: 200,
        data: {
          userInfo: item,
        },
        message: "登录成功",
      };
    } else {
      ctx.body = {
        code: 400,
        data: null,
        message: "验证码错误",
      };
    }
  } else {
    //
    ctx.body = {
      code: 400,
      message: "手机号不正确",
    };
  }
});

module.exports = router;
